# _*_ coding:utf-8 _*_
# @Time  : 2023.07.20
# @Author: zizlee
from fastapi import APIRouter, Depends, Query
from db_utils import BaseDatabaseConnection
from utils.jwt_token import TokenPayload
from constant.user import UserType
from constant.variety import VarietyConstants
from constant.section_scope import SectionScope
from response import APIResponse


class BlockApi:

    def user_block(self, payload: TokenPayload):
        # print(payload.user_type())
        if payload.user_type() not in UserType.SECTION_AUTH_SETS:  # 不再权限范围内
            if payload.user_type() == UserType.REGISTER_USER:
                return APIResponse.success(data={'blocks': []})
            # 全板块权限
            sql = """
                SELECT id,id AS flex_block_id,block_name FROM datlib_flex_block WHERE is_active=1 ORDER BY sort_num;
            """
            prm = None
        else:
            sql = """
                SELECT a.id,a.flex_block_id,a.user_id,b.block_name FROM datlib_flex_block_user As a 
                INNER JOIN datlib_flex_block As b ON a.flex_block_id=b.id
                WHERE a.active_expire>=CURDATE() AND a.user_id=%s 
                ORDER BY b.sort_num;
            """
            prm = [payload.user_id()]
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute(sql, prm)
            blocks = conn.cursor.fetchall()
        return APIResponse.success(data={'blocks': blocks})

    def user_block_variety(self, payload: TokenPayload, block_id: int):
        utp = payload.user_type()
        if utp == UserType.REGISTER_USER:
            return APIResponse.success(data={'variety': []})  # 全无
        # 全有
        a_sql = """
            SELECT id,`code`,`name`,group_id FROM ruizhi_variety WHERE is_active=1 AND FIND_IN_SET('S05',scope) ORDER BY sort_num;
        """
        a_prm = None

        # 看权限
        b_sql = """
            SELECT * FROM datlib_flex_block_variety_user As a
            INNER JOIN ruizhi_variety As b ON a.variety_en=b.code
            WHERE a.active_expire>=CURDATE() AND a.flex_block_id=%s AND a.user_id=%s;
        """
        b_prm = [block_id, payload.user_id()]

        sql = a_sql
        prm = a_prm
        with BaseDatabaseConnection() as conn:
            if utp in UserType.VARIETY_AUTH_SETS:
                # 查询用户是不是全品种
                conn.cursor.execute("SELECT id FROM datlib_flex_block_variety_user WHERE flex_block_id=%s AND variety_en='VAR_ALL' AND user_id=%s AND active_expire>=CURDATE() LIMIT 1;",
                                    [block_id,  payload.user_id()])
                all_access = conn.cursor.fetchone()
                if not all_access:
                    sql = b_sql
                    prm = b_prm
            conn.cursor.execute(sql, prm)
            block_variety = conn.cursor.fetchall()
        for v in block_variety:
            v['is_real'] = True
            v['name'] = f'{v["name"]} ({v["code"]})'
        if len(block_variety) > 10:
            group_variety = []
            for g, gname in VarietyConstants.GROUPS.items():
                g_v_obj = {
                    'name': gname,
                    'code': g,
                    'is_real': False,
                    'children': []
                }
                if g in VarietyConstants.INACTIVE_GROUPS:
                    continue
                for v in block_variety:
                    if v['group_id'] == g:
                        g_v_obj['children'].append(v)
                if len(g_v_obj['children']) > 0:
                    group_variety.append(g_v_obj)
            block_variety = group_variety
        return APIResponse.success(data={'variety': block_variety})

    def user_block_index_group(self, payload: TokenPayload, block_id: int):
        utp = payload.user_type()
        if utp not in UserType.VARIETY_AUTH_SETS:
            if utp == UserType.REGISTER_USER:
                return APIResponse.success(data={'index_groups': []})
            sql = """
                SELECT id as block_group_id,block_id,index_name,frequency,unit,start_date as sd,end_date As ed
                FROM datlib_flex_block_group WHERE is_active=1 ORDER BY sort_num;
            """
            prm = None
        else:
            sql = """
                SELECT b.block_id,b.index_name,b.frequency,b.unit,b.start_date As sd,b.end_date As ed,
                a.id,a.block_group_id,a.lasted_years,a.start_date,a.end_date,a.active_expire
                FROM datlib_flex_block_group_user As a
                INNER JOIN datlib_flex_block_group As b ON a.block_group_id=b.id
                WHERE a.user_id=%s AND a.active_expire>=CURDATE() AND b.block_id=%s AND b.is_active=1
                ORDER BY b.sort_num;
            """
            prm = [payload.user_id(), block_id]
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute(sql, prm)
        block_index_group = conn.cursor.fetchall()
        for g in block_index_group:
            g['flex_type'] = '全量'
            if g.get('start_date'):
                g['flex_type'] = f'始于{g["start_date"]}'
            if g.get('lasted_years'):
                g['flex_type'] = f'最新{g["lasted_years"]}年'
        return APIResponse.success(data={'index_groups': block_index_group})


block_api = APIRouter()


@block_api.get('/')  # 获取当前用户定制的板块
def user_block(payload: TokenPayload = Depends(TokenPayload)):
    return BlockApi().user_block(payload=payload)


@block_api.get('/variety/')  # 获取当前板块的定制品种
def user_block_variety(payload: TokenPayload = Depends(TokenPayload), bid: int = Query(...)):
    return BlockApi().user_block_variety(payload=payload, block_id=bid)


@block_api.get('/indexGroups/')  # 获取当前用户板块下定制的指标组
def user_block_index_group(payload: TokenPayload = Depends(TokenPayload), bid: int = Query(...)):
    return BlockApi().user_block_index_group(payload=payload, block_id=bid)

